package com.lc1993929.mr.join.mapside;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by LiuChang on 2017/12/14/014.
 */
public class MapSideJoin {
    public static class MapSideJoinMapper extends Mapper<LongWritable, Text, Text, NullWritable> {
        private Map<String, String> userMap = new HashMap<>();

        //先获取小表的数据文件，然后加载到内存中
        @Override
        protected void setup(Context context) throws IOException, InterruptedException {
            FileReader fileReader = new FileReader("user.txt");
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line = "";
            while (StringUtils.isNotBlank(line = bufferedReader.readLine())) {
                String[] split = line.split(",");
                userMap.put(split[0], split[1] + "\t" + split[2] + "\t" + split[3]);
            }
        }

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String[] split = line.split(",");
            String userInfo = userMap.get(split[1]);
            context.write(new Text(line + "\t" + userInfo), NullWritable.get());
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException, URISyntaxException {
        Configuration configuration = new Configuration();
        Job job = Job.getInstance(configuration, "mapsidejoindemo");

        job.setJarByClass(MapSideJoin.class);
        job.setMapperClass(MapSideJoinMapper.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(NullWritable.class);

        FileInputFormat.setInputPaths(job, "/join/input/");
        FileOutputFormat.setOutputPath(job, new Path("/join/output/"));

        job.setNumReduceTasks(0);

        job.addCacheFile(new URI("hdfs://hdp1:9000/join/cache/user.txt"));

        boolean waitForCompletion = job.waitForCompletion(true);

        System.exit(waitForCompletion ? 0 : 1);
    }
}
